package models

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
)

type Transaction struct {
	Id            int
	BlockHash     string
	BlockNumber   string
	Confirmations string
	GasUsed       string
	From          string
	Gas           string
	GasPrice      string
	Hash          string
	Nonce         string
	To            string
	Value         string
	Input         string
	Status        string `default:""`
	TimeStamp     string
	Contract      string
	IsDelete      bool `default:false`
}

// 获取本地transactions
func GetTransactions(ethAddr, contract string, offset int) ([]*Transaction, error) {
	var res []*Transaction

	o := orm.NewOrm()
	cond := orm.NewCondition()
	cond1 := cond.And("Contract", contract).And("IsDelete", false).AndCond(cond.And("from", ethAddr).Or("to", ethAddr))
	num, err := o.QueryTable("Transaction").SetCond(cond1).OrderBy("-TimeStamp").Limit(20, offset).All(&res)

	if err != nil || num == 0 {
		logs.Debug("query transaction failed:", err)
		return nil, err
	}

	return res, err
}

// 获取未确认状态的transactions
func GetUnstatusTx() ([]*Transaction, error) {
	var res []*Transaction

	o := orm.NewOrm()
	num, err := o.QueryTable("Transaction").Filter("Status", "").All(&res)

	if err != nil || num == 0 {
		logs.Debug("query transaction failed:", err)
		return nil, err
	}

	return res, err

}

// 获取已成功的tx
func GetSuccessTx() ([]*Transaction, error) {
	var res []*Transaction

	o := orm.NewOrm()
	num, err := o.QueryTable("Transaction").Filter("Status", "1").All(&res)

	if err != nil || num == 0 {
		logs.Debug("query transaction failed:", err)
		return nil, err
	}

	return res, err

}

// 获取需要更新数据的tx
/*func GetUnconfirmedTx() ([]*Transaction, error) {
	var res []*Transaction

	o := orm.NewOrm()
	num, err := o.Raw("SELECT * FROM transaction WHERE status = '1' AND confirmations = '' OR CAST(confirmations AS SIGNED) < 20").QueryRows(&res)
	if err != nil || num == 0 {
		logs.Debug("query transaction failed:", err)
		return nil, err
	}

	return res, err
}*/
